from urllib.parse import quote_plus
from urllib.request import urlopen
from urllib.request import Request
from urllib.parse import urlencode
from urllib.error import URLError
import os, sys
import base64
import json
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

def fetch_token():
    params = {'grant_type': 'client_credentials',
              'client_id': main.API_KEY,
              'client_secret': main.SECRET_KEY}
    post_data = urlencode(params)
    post_data = post_data.encode('utf-8')
    req = Request(main.TOKEN_URL, post_data)
    try:
        f = urlopen(req, timeout=5)
        result_str = f.read()
    except URLError as err:
        print(err)
    result_str = result_str.decode()

    result = json.loads(result_str)

    if ('access_token' in result.keys() and 'scope' in result.keys()):
        if not 'brain_all_scope' in result['scope'].split(' '):
            print ('please ensure has check the  ability')
            exit()
        return result['access_token']
    else:
        print ('please overwrite the correct main.API_KEY and main.SECRET_KEY')
        exit()

def read_file(image_path):
    f = None
    try:
        f = open(image_path, 'rb')
        return f.read()
    except:
        print('read image file fail')
        return None
    finally:
        if f:
            f.close()

def request(url, data):
    req = Request(url, data.encode('utf-8'))
    has_error = False
    try:
        f = urlopen(req)
        result_str = f.read()
        result_str = result_str.decode()
        return result_str
    except  URLError as err:
        print(err)

def main(a, a2_dir=""):

    image_url = main.OCR_URL + "?access_token=" + main.token

    text = ""

    file_read = read_file(a)

    result = request(image_url, urlencode({'image': base64.b64encode(file_read)}))
    result_json = json.loads(result)

    for words_result in result_json["words_result"]:
        text = text + words_result["words"]
    
    
    s5 = "%s.txt" %(os.path.basename(a).rsplit(".", 1)[0])
    with open(os.path.join(a2_dir, s5), mode='w', encoding='utf8') as s8:
        s8.write(text)
    print(text, end='\n\n')

def main2(a):
    if os.path.isdir(a):
        s= "%s.txt" %(os.path.basename(a))
        os.mkdir(s)
        for i in os.listdir(a):
            main(os.path.join(a, i), s)
    else:
        main(a)


if __name__ == '__main__':
    # https://console.bce.baidu.com/ai/#/ai/ocr/app/list
    main.OCR_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"
    main.TOKEN_URL = 'https://aip.baidubce.com/oauth/2.0/token'

    try:
        main.API_KEY = os.environ['API_KEY_3gy6']
        main.SECRET_KEY = os.environ['SECRET_KEY_3gy6']
        main.token = fetch_token()
    except:
        print("\tYou may set API_KEY_3gy6 and SECRET_KEY_3gy6")
        sys.exit()

    if len(sys.argv) <=1:
        print("\tpython *this [*picture]...")
        sys.exit()

    for i in sys.argv[1:]:
        main2(i.strip('\'\"\\').rstrip("/"))
